//
//  YYEEmoticonCollectionCell.swift
//  weibo14
//
//  Created by mac on 16/3/13.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

class YYEEmoticonCollectionCell: UICollectionViewCell {
    
    // 当前cell显示的表情数组.供外界设置
    var emoticons: [YYEEmoticon]? {
        didSet{
            
            // 首先将所有的按钮隐藏
            for value in emoticonButtons {
                value.hidden = true
            }
            
            // 给当前cell身上的表情按钮填充数据
            for (index,emoticon) in emoticons!.enumerate() {
                
                // 1. 取到按钮
                let button = emoticonButtons[index]
                button.hidden = false

                button.emoticon = emoticon
            }
        }
    }

    
    var emoticonButtons = [YYEEmoticonButton]()
    
    var indexPath: NSIndexPath? {
        didSet{
            recentLabel.hidden = indexPath?.section != 0
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        contentView.addSubview(recentLabel)
        
        recentLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-8)
        }

        
        self.backgroundColor = UIColor.whiteColor()
        // 添加表情按钮
        // 添加表情按钮
        addEmoticonButtons()
        contentView.addSubview(deleteButton)
        
        // 添加长按手势
        let ges = UILongPressGestureRecognizer(target: self, action: "longPress:")
        self.addGestureRecognizer(ges)

    }
    
    // 长按手势
    @objc private func longPress(ges:UIGestureRecognizer){
    
        func buttonWithLocation(location: CGPoint) -> YYEEmoticonButton? {
            
            for vale in emoticonButtons {
                // 判断location是否是value.farme的范围内
                if CGRectContainsPoint(vale.frame, location) {
                
                    return vale
                }
            }
            return nil
        }

        // 1. 取到手指所在的点
        let location = ges.locationInView(self)
        // 2. 取到点所对应的表情按钮
        guard let button = buttonWithLocation(location) where button.hidden == false else {
            popView.removeFromSuperview()
            return
        }
        
        // 3. 弹出popView并设置数据
        
        switch ges.state {
        case .Began,.Changed:
            // 取到最后一个window
            let window = UIApplication.sharedApplication().windows.last!
            // 添加到window
            window.addSubview(popView)
            
            // 调整位置
            let rect = button.superview!.convertRect(button.frame, toView: window)
            
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            // 设置数据
            popView.emoticonButton.emoticon = button.emoticon
        default:
            popView.removeFromSuperview()
        }
        
    }
    
    
    /// 添加20个表情按钮
    private func addEmoticonButtons(){
    
        for _ in 0..<20 {
            let button = YYEEmoticonButton()
            
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            
            button.titleLabel?.font = UIFont.systemFontOfSize(35)

            
            contentView.addSubview(button)
            // 将表情按钮添加到数组里面去,以便在下面取到表情按钮调整位置
            emoticonButtons.append(button)
        }
    }
    
    
    // MARK: - 监听事件
    
    /// 删除按钮要执行的方法
    @objc private func deleteButtonClick(){
        print("删除按钮点击了")
        //  发送删除按钮点击的通知
        NSNotificationCenter.defaultCenter().postNotificationName(YYEKeyboardDelDidSelectedNotification, object: nil)
    }

    
    @objc private func emoticonButtonClick(button: YYEEmoticonButton) {

        // 保存表情到最近表情
        YYEEmoticonTools.shareEmoticonTools.saveRecentEmoticon(button.emoticon!)
        
        let popView = YYEEmoticonPopView.popView()
        
        // 把popView加到最上层,取到最上层的window
        let window = UIApplication.sharedApplication().windows.last!
        window.addSubview(popView)
        // 按钮相对于 window 上的位置 重点
        
        // _.converRect(_, toView:_)
        let rect = button.convertRect(button.bounds, toView: window)
        // 设置frame
        popView.center.x = CGRectGetMidX(rect)
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        // 设置数据
        popView.emoticonButton.emoticon = button.emoticon
   
        
        // 过0.25秒之后消失
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            popView.removeFromSuperview()
        }
        // 发送表情点击的通知,并且将表情按钮对应的表情模型通过userInfo传到接收者那儿
        NSNotificationCenter.defaultCenter().postNotificationName(YYEEmoticonDidSelectedNotification, object: nil, userInfo: ["emoticon": button.emoticon!])
        
    }

    
    override func layoutSubviews() {
       
        super.layoutSubviews()
        // 计算每一个表情按钮的宽高
        let itemW = self.frame.width / 7
        let itemH = (self.frame.height - 20) / 3
        
        // 布局子控件
        // 计算20个表情按钮的位置
        for (index,button) in emoticonButtons.enumerate() {
            
            // 计算出该按钮是在第几列第几行
            let col = index % 7
            let row = index / 7
            
            // 计算按钮的位置
            button.frame.origin.x = CGFloat(col) * itemW
            button.frame.origin.y = CGFloat(row) * itemH
            
            // 设置按钮大小
            button.frame.size = CGSize(width: itemW, height: itemH)
        }
        // 设置删除按钮的位置
        deleteButton.frame.origin = CGPoint(x: self.frame.width - itemW, y: itemH * 2)
        // 设置大小
        deleteButton.frame.size = CGSize(width: itemW, height: itemH)
        
       
    }

    
    // MARK: - 懒加载控件
    private lazy var popView: YYEEmoticonPopView = {
        let popView = YYEEmoticonPopView.popView()
        return popView
    }()

    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        return button
    }()
    
    //最近表情里面的说明文字
    private lazy var recentLabel: UILabel = {
        let label = UILabel(textColor: UIColor.lightGrayColor(), fontSzie: 12)
        label.text = "最近使用的表情"
        return label
    }()

}
